package com.sbpm.crmbpm.client.forms.companies;

import com.google.gwt.core.client.GWT;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.text.shared.AbstractSafeHtmlRenderer;
import com.sbpm.crmbpm.client.forms.controls.SelectableListBox;
import com.sbpm.crmbpm.client.handlers.OnFinishEvent;
import com.sbpm.crmbpm.client.resources.css.PersonInfoCss;
import com.sbpm.crmbpm.client.resources.images.ImageResources;
import com.sbpm.crmbpm.client.resources.templates.PersonInfoRenderer;
import com.sbpm.crmbpm.client.services.CompanyManagement;
import com.sbpm.crmbpm.client.services.CompanyManagementAsync;
import com.sbpm.crmbpm.client.util.SimpleAsyncCallback;
import com.sbpm.crmbpm.shared.data.client.*;
import com.sencha.gxt.cell.core.client.SimpleSafeHtmlCell;
import com.sencha.gxt.core.client.IdentityValueProvider;
import com.sencha.gxt.core.client.resources.CommonStyles;
import com.sencha.gxt.core.client.util.Margins;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.data.shared.ModelKeyProvider;
import com.sencha.gxt.theme.base.client.listview.ListViewCustomAppearance;
import com.sencha.gxt.widget.core.client.ListView;
import com.sencha.gxt.widget.core.client.Window;
import com.sencha.gxt.widget.core.client.button.TextButton;
import com.sencha.gxt.widget.core.client.container.*;
import com.sencha.gxt.widget.core.client.event.SelectEvent;
import com.sencha.gxt.widget.core.client.form.FieldLabel;
import com.sencha.gxt.widget.core.client.form.FieldSet;
import com.sencha.gxt.widget.core.client.form.TextField;

public class CompanyForm extends Window
{

    private final CompanyManagementAsync companyManagement = GWT.create( CompanyManagement.class );

    private final BoxLayoutContainer.BoxLayoutData FIELDSET_LAYOUT_DATA = new BoxLayoutContainer.BoxLayoutData( new Margins( 10, 0, 0, 10 ) );

    private TextField companyName;
    private TextField legalName;
    private SelectableListBox segment;
    private TextField inn;
    private TextField ogrn;
    private TextField kpp;

    private ListView<PersonCompanyRel, PersonCompanyRel> personListView;

    private Long companyId;

    private OnFinishEvent onFinishEvent;

    public CompanyForm()
    {
        init();
    }

    protected void init(  )
    {
        setModal( true );
        setBlinkModal( true );
        setWidth( 810 );
        setHeight( 330 );

        setTitle( "Создание компании" );

        VBoxLayoutContainer mainContainer = new VBoxLayoutContainer();
        add( mainContainer );

        final HBoxLayoutContainer formContainer = new HBoxLayoutContainer();
        mainContainer.add( formContainer );

        formContainer.add( createMainInfoSection(), FIELDSET_LAYOUT_DATA );

        formContainer.add( createPersonSection(), FIELDSET_LAYOUT_DATA );

        TextButton okButton = new TextButton( "Сохранить" );
        okButton.addSelectHandler( new SelectEvent.SelectHandler()
        {
            @Override
            public void onSelect( SelectEvent event )
            {
                saveCompany();
            }
        } );

        TextButton cancelButton = new TextButton( "Отмена" );
        cancelButton.addSelectHandler( new SelectEvent.SelectHandler()
        {
            @Override
            public void onSelect( SelectEvent event )
            {
                CompanyForm.this.hide();
            }
        } );

        setButtonAlign( BoxLayoutContainer.BoxLayoutPack.CENTER );

        addButton( okButton );
        addButton( cancelButton );
    }

    public void reset()
    {
        companyId = null;
        companyName.setValue( "" );
        legalName.setValue( "" );
        segment.setSelectedIndex( 0 );
        inn.setValue( "" );
        ogrn.setValue( "" );
        kpp.setValue( "" );
        if( personListView != null )
        {
            personListView.getStore().clear();
        }
    }

    public void show( Long companyId )
    {
        reset();
        if( companyId != null )
        {
            companyManagement.findCompanyWithAllAttributes( companyId, new SimpleAsyncCallback< Company >()
            {
                @Override
                public void onSuccess( Company result )
                {
                    setData( result );
                    show();
                }
            } );
        }
        else
        {
            show();
        }
    }

    public void setData( Company company )
    {
        companyId = company.getId();
        companyName.setValue( company.getName() );
        legalName.setValue( company.getLegalName() );
        if( company.getSegment() != null )
        {
            segment.setValue( company.getSegment().getLabel() );
        }
        inn.setValue( company.getInn() );
        ogrn.setValue( company.getOgrn() );
        kpp.setValue( company.getKpp() );
        if( company.getPersons() != null )
        {
            personListView.getStore().addAll( company.getPersons() );

            personListView.refresh();
        }
    }

    private void saveCompany()
    {
        Company company = new Company();
        company.setId( companyId );
        company.setInn( inn.getCurrentValue() );
        company.setKpp( kpp.getCurrentValue() );
        company.setLegalName( legalName.getCurrentValue() );
        company.setName( companyName.getCurrentValue() );
        company.setOgrn( ogrn.getCurrentValue() );
        if( segment.getSelectedIndex() > 0 )
        {
            company.setSegment( Segment.valueOf( segment.getValue( segment.getSelectedIndex() ) ) );
        }
        company.setType( CompanyType.CLIENT );
        companyManagement.saveCompany( company, new SimpleAsyncCallback()
        {
            @Override
            public void onSuccess( Object result )
            {
                CompanyForm.this.hide();
                if( onFinishEvent != null )
                {
                    onFinishEvent.finish();
                }
            }
        }  );
    }

    private FieldSet createPersonSection()
    {
        FieldSet fieldSet = new FieldSet();
        fieldSet.setHeadingText( "Контакты" );
        fieldSet.setCollapsible( false );
        fieldSet.setWidth( 300 );

        VBoxLayoutContainer fieldSetContainer = new VBoxLayoutContainer();
        fieldSet.add( fieldSetContainer );

        fieldSetContainer.add( createPersonListView() );

        TextButton button = new TextButton();
        button.setIcon( ImageResources.INSTANCE.addIcon() );

        fieldSetContainer.add( button );
        return fieldSet;
    }

    private ListView<PersonCompanyRel, PersonCompanyRel> createPersonListView()
    {
        final PersonInfoRenderer personInfoRenderer = GWT.create(PersonInfoRenderer.class);

        final PersonInfoCss personInfoCss = GWT.create(PersonInfoCss.class);
        personInfoCss.css().ensureInjected();
        final PersonInfoCss.Style style = personInfoCss.css();

        ListViewCustomAppearance<PersonCompanyRel> appearance = new ListViewCustomAppearance<PersonCompanyRel>("." + style.thumbWrap(),
                style.over(), style.select()) {

            @Override
            public void renderEnd(SafeHtmlBuilder builder) {
                String markup = "<div class=\"" + CommonStyles.get().clear() + "\"></div>";
                builder.appendHtmlConstant(markup);
            }

            @Override
            public void renderItem(SafeHtmlBuilder builder, SafeHtml content) {
                builder.appendHtmlConstant("<div class='" + style.thumbWrap() + "' style='border: 1px solid white'>");
                builder.append(content);
                builder.appendHtmlConstant("</div>");
            }

        };

        ModelKeyProvider<PersonCompanyRel> keyProvider = new ModelKeyProvider<PersonCompanyRel>() {
            @Override
            public String getKey(PersonCompanyRel item) {
                return String.valueOf( item.getId() );
            }
        };

        ListStore<PersonCompanyRel> store = new ListStore<PersonCompanyRel>( keyProvider );

        personListView = new ListView<PersonCompanyRel, PersonCompanyRel>(store, new IdentityValueProvider<PersonCompanyRel>() {

            @Override
            public void setValue(PersonCompanyRel object, PersonCompanyRel value) {

            }
        }, appearance);

        personListView.setCell( new SimpleSafeHtmlCell<PersonCompanyRel>( new AbstractSafeHtmlRenderer<PersonCompanyRel>()
        {
            @Override
            public SafeHtml render( PersonCompanyRel object )
            {
                return personInfoRenderer.renderItem( object.getPerson(), style );
            }
        } ) );

        personListView.setBorders( false );
        return personListView;
    }

    private FieldSet createMainInfoSection()
    {
        FieldSet fieldSet = new FieldSet();
        fieldSet.setHeadingText( "Компания" );
        fieldSet.setCollapsible( false );

        VBoxLayoutContainer fieldSetContainer = new VBoxLayoutContainer();
        fieldSet.add( fieldSetContainer );

        companyName = new TextField();
        companyName.setEmptyText( "Введите название компании..." );
        companyName.setWidth( 345 );

        fieldSetContainer.add( new FieldLabel( companyName, "Название компании" ) );

        legalName = new TextField();
        legalName.setEmptyText( "Введите юридическое наименование компании..." );
        legalName.setWidth( 345 );

        fieldSetContainer.add( new FieldLabel( legalName, "Юр. наименование компании" ) );

        HBoxLayoutContainer horizontalLayoutContainer = new HBoxLayoutContainer();

        fieldSetContainer.add( horizontalLayoutContainer );

        VerticalLayoutContainer group1Container = new VerticalLayoutContainer();

        inn = new TextField();
        inn.setEmptyText( "Введите ИНН компании..." );
        group1Container.add( new FieldLabel( inn, "ИНН" ) );

        ogrn = new TextField();
        ogrn.setEmptyText( "Введите ОГРН компании..." );
        group1Container.add( new FieldLabel( ogrn, "ОГРН" ) );

        kpp = new TextField();
        kpp.setEmptyText( "Введите КПП компании..." );
        group1Container.add( new FieldLabel( kpp, "КПП" ) );


        horizontalLayoutContainer.add( group1Container, new BoxLayoutContainer.BoxLayoutData( new Margins( 0, 10, 0, 0 ) ) );

        VBoxLayoutContainer group2Container = new VBoxLayoutContainer();

        segment = new SelectableListBox();
        segment.addItem( "", "" );
        segment.addItem( Segment.HIGH.getLabel(), Segment.HIGH.name() );
        segment.addItem( Segment.MEDIUM.getLabel(), Segment.MEDIUM.name() );
        segment.addItem( Segment.LOW.getLabel(), Segment.LOW.name() );

        group2Container.add( new FieldLabel( segment, "Сегмент" ) );

        horizontalLayoutContainer.add( group2Container );
        return fieldSet;
    }

    public void setOnFinishEvent( OnFinishEvent onFinishEvent )
    {
        this.onFinishEvent = onFinishEvent;
    }
}
